using Autofac.Extensions.DependencyInjection;
using Com.Ctrip.Framework.Apollo;
using Com.Ctrip.Framework.Apollo.Enums;
using Jinjia.Core.API.Extensions;
using Jinjia.Core.ScheduleProvider;
using JinJia.Core.Logger;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;

namespace Jinjia.Approve.ScheduleJobAPI
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("开始启动网站...");
                var host = CreateHostBuilder(args).Build();
                host.Init();
                Console.WriteLine("网站启动完成!");
                host.Run();
            }
            catch (Exception exception)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("网站启动失败");
                Console.WriteLine(exception.ToString());
                Console.ResetColor();
            }
        }

        private static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureApollo(args)
                .ConfigureLogging((hostingContext, logging) =>
                {
                    logging.ClearProviders();
                    logging.AddJinJiaLogger();
                })
                .ConfigureAutofac()
                .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });

        private static void Init(this IHost host)
        {
            using var scope = host.Services.CreateScope();
            var service = scope.ServiceProvider.GetRequiredService<IScheduleJobService>();
            service.RegisterScheduleJob();
        }

        private static IHostBuilder ConfigureApollo(this IHostBuilder builder)
        {
            return builder.ConfigureAppConfiguration((hostingContext, configurationBuilder) =>
            {
                configurationBuilder
                    .AddApollo(hostingContext.Configuration.GetSection("apollo"))
                    .AddDefault(ConfigFileFormat.Json);
            });
        }

        private static IHostBuilder ConfigureAutofac(this IHostBuilder builder)
        {
            //使用autofac的容器工厂替换系统默认的容
            return builder.UseServiceProviderFactory(new AutofacServiceProviderFactory());
        }
    }
}